<template>
  <el-dialog
    :model-value="show"
    :title="rowList.name === '' ? '添加角色' : '编辑角色'"
    width="420"
    @close="emit('hidden')"
  >
    <el-form :model="form">
      <el-form-item label="角色名称:">
        <el-input
          placeholder="请输入角色名称"
          v-model="form.name"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="描述:" style="text-indent: 2em">
        <el-input
          v-model="form.description"
          :rows="3"
          type="textarea"
          placeholder="请输入描述"
        />
      </el-form-item>
      <el-form-item label="是否启用:">
        <el-radio-group v-model="form.status" class="ml-4">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('hidden')">取消</el-button>
        <el-button type="primary" @click="addEdit">确定</el-button>
      </span>
    </template>
  </el-dialog>
  
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, watch } from "vue";
import { addRoleApi, editRoleApi } from "../api";
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  rowList: {
    type: Object,
    default: {},
  },
});
watch(
  props.rowList,
  () => {
    if (props.rowList.name && props.rowList.description) {
      Object.assign(form, props.rowList);
    } else {
      Object.assign(form, props.rowList);
    }
  },
  { deep: true }
);

const emit = defineEmits(["hidden"]);
const form = reactive<{ name: string; description: string; status: number }>({
  name: "",
  description: "",
  status: 0,
});
const addRoleFn = () => {
  ElMessageBox.confirm("确定要添加新角色吗?", "提示", {
    confirmButtonText: "是的",
    cancelButtonText: "不了",
    type: "warning",
    draggable: true,
  })
    .then(() => {
      addRoleApi(form).then((res) => {
        if (res.code === 200) {
          ElMessage.success("添加成功");
          emit("hidden", true);
        } else {
          emit("hidden");
        }
      });
    })
    .catch(() => {});
};
const editFn = () => {
  ElMessageBox.confirm("编辑当前角色吗?", "提示", {
    confirmButtonText: "是的",
    cancelButtonText: "不了",
    type: "warning",
    draggable: true,
  })
    .then(() => {
      editRoleApi(form);
      ElMessage.success("修改成功");
      emit("hidden", true);
    })
    .catch(() => {});
};
const addEdit = () => {
  if (props.rowList.name && props.rowList.description) {
    editFn();
  } else {
    addRoleFn();
  }
};
</script>

<style lang="scss" scoped></style>
